package com.tanhua.server.service;

import cn.hutool.core.collection.CollUtil;
import com.tanhua.dubbo.api.RecommendUserApi;
import com.tanhua.dubbo.api.UserInfoApi;
import com.tanhua.model.domain.UserInfo;
import com.tanhua.model.dto.RecommendUserDto;
import com.tanhua.model.mongo.RecommendUser;
import com.tanhua.model.vo.PageResult;
import com.tanhua.model.vo.TodayBest;
import com.tanhua.server.interceptor.UserHolder;
import org.apache.dubbo.config.annotation.DubboReference;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

@Service
public class TanhuaService {

    @DubboReference
    private RecommendUserApi recommendUserApi;

    @DubboReference
    private UserInfoApi userInfoApi;

    public TodayBest todayBest() {
        Long userId = UserHolder.getUserId();
        RecommendUser recommendUser = recommendUserApi.queryWithMaxScore(userId);
        UserInfo userInfo = userInfoApi.findById(recommendUser.getUserId());

        TodayBest init = TodayBest.init(userInfo, recommendUser);
        return init;
    }

    public PageResult recommendation(RecommendUserDto dto) {
        Long userId = UserHolder.getUserId();
        PageResult pr = recommendUserApi.queryRecommendUser(dto.getPage(), dto.getPagesize(), userId);
        List<RecommendUser> items = (List<RecommendUser>) pr.getItems();
        if (items == null) {
            return pr;
        }
        ArrayList<TodayBest> todayBests = new ArrayList<>();
        /**
         * 下方代码冗余，for循环每次都查一次数据库，重新改造后程下方所示
         */
        /** for (RecommendUser item : items) {
         Long recommendUserId = item.getUserId();
         UserInfo userInfo = userInfoApi.findById(recommendUserId);
         if (userInfo != null) {
         if (!StringUtils.isEmpty(dto.getGender()) && !dto.getGender().equals(userInfo.getGender())) {
         continue;
         }
         if (dto.getAge() != null && dto.getAge() < userInfo.getAge()) {
         continue;
         }
         TodayBest vo = TodayBest.init(userInfo, item);
         todayBests.add(vo);
         }
         }
         pr.setItems(todayBests);
         return pr; */
        List<Long> userIds = CollUtil.getFieldValues(items, "userId", Long.class);
        UserInfo userInfo = new UserInfo();
        // 只设置两个练习，更多参数添加后面自己看着添加
        userInfo.setAge(dto.getAge());
        userInfo.setGender(dto.getGender());
        Map<Long, UserInfo> userInfoMap = userInfoApi.findByIds(userIds, userInfo);
        for (RecommendUser item : items) {
            Long id1 = item.getUserId();
            UserInfo info = userInfoMap.get(id1);
            if (info != null) {
                TodayBest init = TodayBest.init(info, item);
                todayBests.add(init);
            }

        }
        pr.setItems(todayBests);
        return pr;
    }
}
